import store from '../store/store'
import axios from './http'
import wx from 'weixin-js-sdk'
import $ from 'edom'

const api = {
  // 微信定位
  location: (callback) => {
    let ua = window.navigator.userAgent.toLowerCase()
    if (ua.indexOf('micromessenger') === -1) {
      // 不是微信环境
      store.commit('setLocation', {lat: 30.26, lng: 120.19})
      callback()
      return
    }
    axios.post('/api/home/location', {
      url: window.location.href.split('#')[0]
    })
    .then((res) => {
      let data = res.data.desc
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: `${data.nonceStr}`,
        signature: data.signature,
        jsApiList: [
          'getLocation'
        ]
      })
      wx.ready(() => {
        wx.getLocation({
          type: 'wgs84',
          success: (res) => {
            store.commit('setLocation', {lat: res.latitude, lng: res.longitude})
            callback()
          },
          cancel: () => {
            store.commit('setLocation', {lat: 30.26, lng: 120.19})
            callback()
          },
          fail: () => {
            store.commit('setLocation', {lat: 30.26, lng: 120.19})
            callback()
          }
        })
      })
    })
  },
  // 首页轮播图
  getBannerImg: () => {
    axios.get('/api/home/banner_list')
    .then((res) => {
      let data = res.data
      store.commit('cacheSwipers', data.banner_list)
    })
  },
  // 首页获取推荐商家
  getBusinessLists: (callback) => {
    axios.post('/api/home/recommend_list', {
      lng: store.state.lng,
      lat: store.state.lat
    })
    .then((res) => {
      let data = res.data
      callback(data)
    })
  },
  // 个人中心获取个人的信息
  getUserInfo: () => {
    axios.post('/api/user/index', {
      user_id: store.state.user_id,
      token: store.state.token
    })
    .then((res) => {
      let data = res.data
      let desc = data.desc
      store.commit('userInfo', desc)
    })
  },
  // 个人中心获取新消息
  hasNewMsg: (callback) => {
    axios.post('/api/user/has_new_msg', {
      user_id: store.state.user_id,
      token: store.state.token
    })
    .then((res) => {
      let data = res.data
      let code = data.code
      if (code === 200) {
        callback()
      }
    })
  },
  // 获取芝麻分协议
  getZMContract: (callback) => {
    axios.get('/api/zhimaContract/get_detail', {
      user_id: store.state.user_id,
      token: store.state.token
    })
    .then((res) => {
      let data = res.data
      callback(data.content)
    })
  },
  // 获取客服电话
  getServicePhone: () => {
    axios.post('/api/home/service', {
      user_id: store.state.user_id,
      token: store.state.token
    })
    .then((res) => {
      let phone = res.data.desc.tel
      store.commit('cacheServicePhone', phone)
    })
  },
  // 获取提前还款列表
  getRepayList: () => {
    axios.post('/api/loanRepay/prepayment_list', {
      user_id: store.state.user_id,
      token: store.state.token
    }).then((res) => {
      let data = res.data
      let desc = data.desc
      if (data.code === 200) {
        store.commit('getpreRepayList', {total: desc.num, lists: desc.result})
      } else {
        store.commit('getpreRepayList', {total: 0, lists: []})
      }
    })
  },
  // 获取丰期信息
  getBillDetail: () => {
    axios.post('/api/loanRepay/index', {
      user_id: store.state.user_id,
      token: store.state.token
    }).then((res) => {
      let data = res.data
      store.commit('getBillDetail', data.desc)
    })
  },
  // 获取七牛云token
  getQNYToken: () => {
    return new Promise((resolve) => {
      axios.post('/api/qiniu/get_up_token', {
        user_id: store.state.user_id,
        token: store.state.token
      })
      .then((res) => {
        let data = res.data
        let code = data.code
        let desc = data.desc
        if (code === 200) {
          resolve(desc)
        } else {
          $().Mnews(desc, 1000)
        }
      })
    })
  },
  // 获取图片上传七牛云后所得的key
  getQNYKey: (base64Img, QNYtoken) => {
    return new Promise((resolve) => {
      const url = 'http://upload.qiniu.com/putb64/-1'
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          let data = JSON.parse(xhr.responseText)
          resolve(data.key)
        }
      }
      xhr.open('POST', url, true)
      xhr.setRequestHeader('Content-Type', 'application/octet-stream')
      xhr.setRequestHeader('Authorization', 'UpToken ' + QNYtoken)
      xhr.send(base64Img)
    })
  },
  // 上传用户的基本信息
  saveUserBase: (callback) => {
    axios.post('/api/user/save', Object.assign({
      user_id: store.state.user_id,
      token: store.state.token
    }, store.state.profile.base))
    .then((res) => {
      let data = res.data
      callback(data)
    })
  },
  // TODO 全额支付 -> 微信支付
  totalPay: (money, id) => {
    axios.post('/api/order/full_payout', {
      user_id: store.state.user_id,
      token: store.state.token,
      total_money: money,
      sid: id
    }).then((res) => {
      let data = res.data
      if (data.code === 200) {
        axios.post('/api/wxpay/index', {
          user_id: store.state.user_id,
          token: store.state.token,
          out_trade_no: data.desc
        }).then((res) => {
          let data = res.data
          let params = data.desc
          console.log(params)
          if (typeof WeixinJSBridge === 'undefined') {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', wxpay, false)
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', wxpay)
              document.attachEvent('onWeixinJSBridgeReady', wxpay)
            }
          } else {
            wxpay()
          }
          function wxpay () {
            /* eslint-disable */
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest', {
                'appId': params.appId,
                'timeStamp': params.timeStamp,
                'nonceStr': params.nonceStr,
                'package': params.package,
                'signType': params.signType,
                'paySign': params.paySign
              }, function (res) {
                if (res.err_msg === 'get_brand_wcpay_request:ok' ) {
                  location.href = '#/mine'
                }
              }
            )
          }
        })
      } else {
        $().Mnews(data.desc, 2000)
      }
    })
  }
}

export default api
